<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/17
 * Time: 15:07
 */
namespace App\Http\Admin\Stock\Controllers;

use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Website\Models\Menu;
use App\Eloquent\Ygt\Stock;
use App\Eloquent\Ygt\StockIn;
use App\Eloquent\Ygt\Category;
use App\Eloquent\Ygt\Product;
use App\Engine\Stock as StockEngine;

class IndexController extends Controller
{

    public function getStockList()
    {
        $adminUser          = request()->user('admin')->toArray();
        $company_id         = $adminUser['company_id'];
        if (request()->isMethod('post')) {
            $where = [];

            if ($productName = request('product_name')) {
                $where['ygt_product.product_name'] = ['like', '%' . $productName . '%'];
            }

            if ($productNo = request('product_no')) {
                $where['ygt_product.product_no'] = $productNo;
            }

            if ($categoryId = request('category_id')) {
                $categoryIds = explode(',', $categoryId);
                foreach($categoryIds as $v){
                    $categoryModel = new Category();
                    $categoryArr = $categoryModel->getCategoryOption($v,$company_id);
                    $category = collect($categoryArr);

                    $tempCategoryIds = $category->map(function ($c) {
                        return $c['id'];
                    })->toArray();
                    $categoryIds = array_merge($categoryIds,$tempCategoryIds);
                }
                $categoryIds = array_unique($categoryIds);
                $where['category_id'] = ['in',$categoryIds];
            }

            if ($stockType = request('stock_type')) {
                $where['stock_type'] = $stockType;
            }


            $where['ygt_stock.company_id'] = $company_id;


            $stockModel = new Stock();
            $field = 'ygt_stock.id,'.
                'ygt_stock.water_no,'.
                'ygt_stock.product_id,'.
                'ygt_stock.number,'.
                'ygt_stock.relate_type,'.
                'ygt_stock.relate_id,'.
                'ygt_stock.type,'.
                'ygt_stock.stock_type,'.
                'ygt_stock.created_at,'.
//                'ygt_stockin.distribution_company,'.
//                'ygt_stockin.contact_number,'.
                'ygt_product.product_name,'.
                'ygt_product.product_no';


            $pageSize       = request('pageSize', 20);
            $pageCurrent    = request('pageCurrent', 1);
            $offset         = ($pageCurrent - 1) * $pageSize;

            $join = [
//                ['table'=>'ygt_stockin','field_l'=>'ygt_stockin.stock_id','field_c'=>'=','field_r'=>'ygt_stock.id'],
                ['table'=>'ygt_product','field_l'=>'ygt_product.id','field_c'=>'=','field_r'=>'ygt_stock.product_id']
            ];
//            $stockList = $stockModel->getStockList($where, $field, $pageSize, $offset);
            $stockList = $stockModel->getData( $where, $field, $pageSize, $offset, '', '', $join );
//            $stockList->transform(function ($item, $key) {
////                dd($item->created_at);
////                $item['created_at'] = date('Y-m-d H:i:s',$item['created_at']);
//                $item->created_time = $item->created_at->formatLocalized('%Y-%m-%d %H:%M:%S');
//                return $item;
//            });

            $count = $stockModel->getCount($where, $join);

            $result = collect(['totalRow'=>$count,'pageCurrent'=>$pageCurrent,'list'=>$stockList]);

            return $result->toJson();
        }

        $categoryModel = new Category();
        $category = $categoryModel->getCategoryOption(0,$company_id);
        $catelist = [];
        foreach($category as $k=>$v){
            $catelist[$v['id']] = str_repeat('└―',$v['level']).$v['cat_name'];
        }
        $optionHtml = '';
        foreach($catelist as $k => $v){
            $optionHtml .= '<option value="'.$k.'">'.$v.'</option>';
        }
        $catejson = json_encode($catelist);

        $stockType = [
            1=>"厂内入库",
            2=>"厂外入库",
            3=>"厂内出库",
            4=>"厂外出库"
        ];
        $stockTypeJson = json_encode($stockType);


        return $this->view('list', compact('catejson','optionHtml','stockTypeJson','stockType'));
    }

    public function stockIn()
    {
        $input = request()->only('product_no', 'number', 'remark', 'unit_price');
        if (request()->isMethod('post')) {
            $productModel = new Product();
            $productInfo = $productModel->getProductInfoByNo($input['product_no']);
            if (!$productInfo or !$productInfo->toArray()) {
                return $this->ajaxFail(get_error_message(ERR_PRODUCT_NOT_EXIST));
            }

            $stockModel = new Stock();
            $water_no = StockEngine::createWaterNo();
            $stockData = ['number' => $input['number'], 'product_id' => $productInfo->id, 'stock_type'=>2, 'remark' => $input['remark'], 'water_no' => $water_no];

            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];
            $stockData['company_id'] = $company_id;


            if ($stockId = $stockModel->addStock($stockData)) {

                $stockInData = [
                    'stock_id' => $stockId,
                    'unit_price' => $input['unit_price']?$input['unit_price']:0,
                ];

                $stockInModel = new StockIn();
                $stockInModel->addStock($stockInData);

                //库存累加
                if (!$productModel->addNumber($productInfo->id, $input['number'])) {
                    return $this->ajaxFail(get_error_message(ERR_PRODUCT_INCREMENT_FAIL));
                }
            }
            return $this->ajaxSuccess('保存成功');

        }
            return $this->view('in');
    }

    public function saveProduct(Request $request)
    {
        $params = $this->jsonRequest();
        $input = $request->all();
        try {
            $user = new Product();
            $result = (isset($input['addFlag']) && $input['addFlag'])
                ? $user->addProduct($input)
                : $user->updateProduct($input);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }

        return $this->jsonReturn($result);
    }

    public function purchaseInfo(){
        $id = request('id');
        $info = StockIn::where('id',$id)->select([
            'id',
            'unit_price',
            'distribution_company',
            'distribution_time',
            'contact_number',
        ])->first();

        $relateType = StockEngine::getRelateType(3);
        $where = ['relate_type'=>3,'relate_id'=>$id];


        $stockInfo = Stock::getOneData($where);

        $productInfo = Product::where('id',$stockInfo->product_id)->first();

        $info->number = $stockInfo->number;
        $info->spec = $productInfo->spec;
        $info->img_url = url('api/service/stock/qrcode?water_no='.$stockInfo->water_no);

        $info->distribution_time = date('Y-m-d H:i:s',$info->distribution_time);

        return $this->view('info',compact('info','productInfo'));

    }

}